# coding=utf8
# %%
import traceback
import logging
from functools import wraps
import traceback
import datetime


def LOGGER():
    ''' Output log to file and console '''
    # Define a Handler and set a format which output to file
    logging.basicConfig(
        level=logging.DEBUG,  # 定义输出到文件的log级别，
        # 定义输出log的格式
        format='time: %(asctime)s level: %(levelname)s\n \
                path: %(pathname)s --> line: %(lineno)d  \n \
                massage: %(message)s \n \
                ',
        datefmt='%Y-%m-%d %H:%M:%S',                                     # 时间
        filename='_logFile.log',  # log文件名
        filemode='a'  # 写入模式“w”或“a”
    )
    # Define a Handler and set a format which output to console
    console = logging.StreamHandler()                  # 定义console handler
    console.setLevel(logging.INFO)                     # 定义该handler级别
    formatter = logging.Formatter(
        '%(asctime)s : %(levelname)s  %(message)s', "%Y%m%d-%H:%M:%S")  # 定义该handler格式
    console.setFormatter(formatter)
    logging.getLogger().addHandler(console)
    return logging


def setlogging(func):
    '''
    通过装饰器实现logging
    @logger.setlogging
    '''
    # @wraps(func)
    def wrapper(*args, **kwargs):
        logger = LOGGER()
        name = func.__name__
        try:
            a = func(*args, **kwargs)
            logger.info('name: function {}()'.format(name))
            logger.debug('{}\n{}'.format(name, a))
            return a
        except Exception as e:

            logger.critical('{}() error --> line {}'.format(name, e))
            traceback.print_exc(file=open('log.txt', 'a'))

    return wrapper


if __name__ == "__main__":

    @setlogging
    def test(X, Y, Z):
        print(X)
        a = Y + Z
        return a
    a = test('a', 1, '2')
    print(a)
# %%
